﻿
Partial Class WebForm_ManageRole_SearchRoleOrganizationMappingByRole
    Inherits System.Web.UI.UserControl

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.Visible = True

        If Not IsPostBack Then
            Me.BindData()
        End If
    End Sub

    Protected Sub chkAll_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim chkAll As CheckBox = TryCast(sender, CheckBox)
        Dim cellIndex = Me.gv.HeaderRow.Cells.GetCellIndex(chkAll.Parent)

        Me.AddAllRoleAuthMapping(chkAll)
        Me.Show(Me.RoleID)
    End Sub

    Protected Sub chk_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim chk As CheckBox = TryCast(sender, CheckBox)

        Me.AddRoleAuthMapping(chk)
        Me.Show(Me.RoleID)
    End Sub

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnSave.Click
        'Me.SaveData()
        'Me.AddRoleAuthMapping()
        'Me.Show(Me.RoleID)
    End Sub

    Protected Sub gv_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gv.PageIndexChanging
        Me.gv.PageIndex = e.NewPageIndex
        Me.Show(Me.RoleID)
    End Sub


    Protected Sub btnQuery_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnQuery.Click
        Me.Show(Me.RoleID)
    End Sub
End Class

Partial Class WebForm_ManageRole_SearchRoleOrganizationMappingByRole
    Private authList() As String = {"Query", "Add", "Edit", "Delete", "Print", "Admin"}

    ''' <summary>
    ''' 僅顯示，不重載資料
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub Show()
        Me.mpSearch.Show()
        Me.Visible = True
    End Sub

    ''' <summary>
    ''' 顯示且重載資料
    ''' </summary>
    ''' <param name="roleID"></param>
    ''' <remarks></remarks>
    Public Sub Show(ByVal roleID As String)
        Me.RoleID = roleID
        Me.lblRoleName.Text = Me.RoleName

        If Me.Check() = False Then
            Return
        End If

        Me.BindData()
        Me.BindGV()
        'Me.BindCHL()

        Me.mpSearch.Show()
        Me.Visible = True
    End Sub

    Private Function Check() As Boolean
        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        sql.AppendFormat("select * from FD_Role r ")
        sql.AppendFormat("where r.RoleID = {0} ", Me.RoleID)

        If dat.GetData(sql).Rows(0)("Virtual") = "Y" Then
            MyObj.ShowMessage("虛擬角色不可設定單位權限")
            Return False
        Else
            Return True
        End If

    End Function

    Private Sub BindData()
        If clsAuth.GetTableAuth("RoleOrganizationMapping", "Edit") = False Then
            Me.btnSave.Enabled = False
        Else
            Me.btnSave.Enabled = True
        End If

    End Sub

    ''' <summary>
    ''' depreciated
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub BindCHL()
        'Dim dat As New clsData
        'Dim sql As New MyStringBuilder
        'Dim dt As Data.DataTable

        'dt = MyObj.GetCodeMappingData("RoleOrganizationMapping", "AuthName")

        'Me.chl.Items.Clear()
        'For Each auth As String In authList
        '    dt.DefaultView.RowFilter = String.Format("Value='{0}'", auth)

        '    Dim li As New ListItem
        '    li.Text = dt.DefaultView(0)("Text")
        '    li.Value = dt.DefaultView(0)("Value")

        '    Me.chl.Items.Add(li)
        'Next

        'sql.Length = 0
        'sql.AppendFormat("select ro.* ")
        'sql.AppendFormat("from RoleOrganizationMapping ro ")
        'sql.AppendFormat("where ro.RoleID = {0} ", Me.RoleID)

        'dt = dat.GetData(sql)

        'For Each li As ListItem In Me.chl.Items
        '    dt.DefaultView.RowFilter = String.Format("AuthName='{0}'", li.Value)

        '    If dt.DefaultView.Count > 0 Then
        '        li.Selected = True
        '    End If
        'Next

    End Sub

    Private Function SaveData() As Boolean
        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        Using scope As New Transactions.TransactionScope
            sql.Length = 0
            sql.AppendFormat("delete FD_RoleOrganizationMapping ")
            sql.AppendFormat("where RoleID = {0} ", Me.RoleID)
            dat.AccData(sql)

            For Each li As ListItem In Me.chl.Items

                If li.Selected = True Then
                    sql.Length = 0
                    sql.AppendFormat("insert FD_RoleOrganizationMapping(RoleID,AuthName) select ")
                    sql.AppendFormat(" '{0}' ", Me.RoleID)
                    sql.AppendFormat(",'{0}' ", li.Value)

                    dat.AccData(sql)

                End If
            Next
            scope.Complete()
        End Using

        Return True
    End Function

    Private Sub BindGV()
        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        sql.Length = 0
        sql.AppendFormat("select distinct o.* ")
        sql.AppendFormat(", 'Query' as QueryAccess ")
        sql.AppendFormat(", 'Add' as AddAccess ")
        sql.AppendFormat(", 'Edit' as EditAccess ")
        sql.AppendFormat(", 'Delete' as DeleteAccess ")
        sql.AppendFormat(", 'Print' as PrintAccess ")
        sql.AppendFormat(", 'Admin' AdminAccess ")
        sql.AppendFormat("from FD_OrganizationView o ")

        Dim parent As Integer = clsAuth.GetParentRoleID(Me.RoleID)

        If Me.RoleID <> parent Then
            '只能修改父群組有的權限 - 先排除父群組沒有的列
            sql.AppendFormat("inner join FD_RoleOrganizationMappingView ro on o.OrganizationID = ro.OrganizationID and o.VOrganizationID = ro.VOrganizationID ")
            sql.AppendFormat("where o.Active = 'Y' ")
            sql.AppendFormat("and ro.RoleID = {0} ", parent)
        Else
            sql.AppendFormat("where o.Active = 'Y' ")
        End If

        sql.AppendFormat(Me.GetWhereSQL())

        Me.gv.DataSource = dat.GetData(sql.ToString(), Nothing, Data.CommandType.Text, "dt")
        Me.gv.DataBind()

        '只能修改父群組有的權限 - 在畫面上停用父群組沒有的選項

        If Me.RoleID <> parent Then
            sql.Length = 0
            sql.AppendFormat("select ro.* from FD_RoleOrganizationMappingView ro ")
            sql.AppendFormat("where ro.RoleID = '{0}' ", parent)

            Dim parentMappings As Data.DataTable = dat.GetData(sql)

            For Each row As GridViewRow In Me.gv.Rows
                Dim key As DataKey = Me.gv.DataKeys(row.RowIndex)

                For Each auth As String In Me.authList

                    Dim chkAuth As CheckBox = TryCast(row.FindControl("chk" + auth), CheckBox)
                    Dim cellIndex = row.Cells.GetCellIndex(chkAuth.Parent)
                    Dim chkAll As CheckBox = TryCast(Me.gv.HeaderRow.Cells(cellIndex).Controls(1), CheckBox)

                    parentMappings.DefaultView.RowFilter = String.Format("OrganizationID = {0} and VOrganizationID = {1} and AuthName = '{2}' ", key("OrganizationID"), key("VOrganizationID"), auth)

                    If parentMappings.DefaultView.Count = 0 Then
                        chkAuth.Visible = False
                        chkAuth.Checked = False
                    End If
                Next
            Next
        End If

        sql.Length = 0
        sql.AppendFormat("select ro.* from FD_RoleOrganizationMappingView ro ")
        sql.AppendFormat("where ro.RoleID = '{0}' ", Me.RoleID)

        Dim mappings As Data.DataTable = dat.GetData(sql)

        For Each row As GridViewRow In Me.gv.Rows
            Dim key As DataKey = Me.gv.DataKeys(row.RowIndex)

            For Each auth As String In Me.authList

                Dim chkAuth As CheckBox = TryCast(row.FindControl("chk" + auth), CheckBox)
                Dim cellIndex = row.Cells.GetCellIndex(chkAuth.Parent)
                Dim chkAll As CheckBox = TryCast(Me.gv.HeaderRow.Cells(cellIndex).Controls(1), CheckBox)

                mappings.DefaultView.RowFilter = String.Format("OrganizationID = '{0}' and VOrganizationID = {1} and AuthName = '{2}' ", key("OrganizationID"), key("VOrganizationID"), auth)

                If mappings.DefaultView.Count > 0 Then
                    chkAuth.Checked = True
                Else
                    chkAuth.Checked = False
                End If

            Next
        Next

        '判斷全選選項是否啟用，或打勾
        For Each auth As String In authList
            sql.Length = 0
            sql.AppendFormat("select isnull(count(*),0) from FD_RoleOrganizationMapping ro ")
            sql.AppendFormat("where ro.AuthName='{0}' ", auth)
            sql.AppendFormat("and ro.RoleID = {0} ", parent)

            Dim parentCount As Integer = dat.GetData(sql).Rows(0)(0)

            sql.Length = 0
            sql.AppendFormat("select isnull(count(*),0) from FD_RoleOrganizationMapping ro ")
            sql.AppendFormat("where ro.AuthName='{0}' ", auth)
            sql.AppendFormat("and ro.RoleID = {0} ", Me.RoleID)

            Dim childCount As Integer = dat.GetData(sql).Rows(0)(0)

            Dim chkAll As CheckBox = TryCast(Me.gv.HeaderRow.FindControl("chkAll" + auth), CheckBox)

            If childCount < parentCount OrElse parentCount = 0 Then
                chkAll.Checked = False
            Else
                chkAll.Checked = True
            End If

        Next
    End Sub

    Private Function GetWhereSQL() As String
        Dim sql As New MyStringBuilder

        If Me.txtOrganizationName.Text <> "" Then
            sql.AppendFormat("and o.OrganizationName like '%{0}%' ", Me.txtOrganizationName.Text)
        End If

        Return sql.ToString()
    End Function

    Private Function AddRoleAuthMapping(ByVal chkAuth As CheckBox) As Boolean
        Dim sql As New System.Text.StringBuilder
        Dim dat As New clsData

        Using scope As New Transactions.TransactionScope

            Dim row As GridViewRow = TryCast(chkAuth.NamingContainer, GridViewRow)
            Dim key As DataKey = Me.gv.DataKeys(row.RowIndex)
            Dim auth As String = Me.FindAuth(chkAuth.ID)

            If chkAuth.Checked = True Then
                sql.Length = 0
                sql.AppendFormat("insert FD_RoleOrganizationMapping (RoleID,OrganizationID,VOrganizationID,AuthName) select ")
                sql.AppendFormat(" '{0}' ", Me.RoleID)
                sql.AppendFormat(",'{0}' ", key("OrganizationID"))
                sql.AppendFormat(",'{0}' ", key("VOrganizationID"))
                sql.AppendFormat(",'{0}' ", auth)

                dat.AccData(sql.ToString, Nothing, Data.CommandType.Text)
            Else
                sql.Length = 0
                sql.AppendFormat("delete FD_RoleOrganizationMapping ")
                sql.AppendFormat("where RoleID = '{0}' ", Me.RoleID)
                sql.AppendFormat("and OrganizationID = '{0}' ", key("OrganizationID"))
                sql.AppendFormat("and VOrganizationID = '{0}' ", key("VOrganizationID"))
                sql.AppendFormat("and AuthName = '{0}' ", auth)

                dat.AccData(sql.ToString, Nothing, Data.CommandType.Text)
            End If

            scope.Complete()
        End Using

        'clsAuth.BuildRoleOrganizationMappingData()
        clsAuth.RebuildRoleOrganizationMapping()

        Return True
    End Function

    Private Function AddAllRoleAuthMapping(ByVal chkAuth As CheckBox) As Boolean
        Dim sql As New System.Text.StringBuilder
        Dim dat As New clsData

        Dim auth = Me.FindAuth(chkAuth.ID)

        Using scope As New Transactions.TransactionScope

            sql.Length = 0
            sql.AppendFormat("delete FD_RoleOrganizationMapping ")
            sql.AppendFormat("where RoleID = '{0}' ", Me.RoleID)
            sql.AppendFormat("and AuthName = '{0}' ", auth)

            dat.AccData(sql.ToString, Nothing, Data.CommandType.Text)

            If chkAuth.Checked = True Then
                sql.Length = 0
                sql.AppendFormat("insert FD_RoleOrganizationMapping (RoleID,OrganizationID,VOrganizationID,AuthName) select ")
                sql.AppendFormat(" '{0}' ", Me.RoleID)
                sql.AppendFormat(",{0} ", "OrganizationID")
                sql.AppendFormat(",{0} ", "VOrganizationID")
                sql.AppendFormat(",'{0}' ", auth)

                Dim parent As Integer = clsAuth.GetParentRoleID(Me.RoleID)

                '全選，新增所有父權限
                If Me.RoleID = parent Then
                    sql.AppendFormat("from FD_OrganizationView ")
                    sql.AppendFormat("where Active = 'Y' ")
                Else
                    sql.AppendFormat("from FD_RoleOrganizationMappingView ro ")
                    sql.AppendFormat("where ro.RoleID = {0} ", parent)
                    sql.AppendFormat("and ro.AuthName = '{0}' ", auth)
                End If

                dat.AccData(sql.ToString, Nothing, Data.CommandType.Text)

            End If

            scope.Complete()
        End Using

        clsAuth.RebuildRoleOrganizationMapping()

        Return True
    End Function

    Private Function FindAuth(ByVal searchText As String) As String
        For Each auth As String In Me.authList
            If searchText.Contains(auth) Then
                Return auth
            End If
        Next

        Return ""
    End Function

    Public Property RoleID() As String
        Get
            Return ViewState("RoleID")
        End Get
        Set(ByVal value As String)
            ViewState("RoleID") = value

            Dim sql As New MyStringBuilder
            Dim dat As New clsData

            sql.AppendFormat("select RoleDescription from FD_Role where RoleID = {0} ", Me.RoleID)

            Me.RoleName = dat.GetData(sql).Rows(0)(0)
        End Set
    End Property

    Public Property RoleName() As String
        Get

            Return ViewState("RoleName")
        End Get
        Set(ByVal value As String)
            ViewState("RoleName") = value
        End Set
    End Property
End Class